package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.support.AuthSupport;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsStorage;
import com.qiguliuxing.dts.service.base.DtsStorageService;
import com.qiguliuxing.dts.service.third.StorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/storage")
@Validated
@Api(tags= ApiAdminConsts.Storage.PARENT)
public class AdminStorageController {
	private static final Logger logger = LoggerFactory.getLogger(AdminStorageController.class);

	@Autowired
	private StorageService storageService;
	@Autowired
	private DtsStorageService dtsStorageService;

	@RequiresPermissions("admin:storage:list")
	@RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Storage.LIST)
	@GetMapping("/list")
	@WebLog(description = ApiAdminConsts.Storage.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "对象key") String key,
					   @ApiParam(value = "对象名称") String name,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsStorage> storageList = dtsStorageService.querySelective(key, name, page, limit, sort, order);
		long total = PageInfo.of(storageList).getTotal();
		Map<String, Object> data = new HashMap<>();
		data.put("total", total);
		data.put("items", storageList);
		return ResponseUtils.ok(data);
	}

	@PostMapping("/create")
	@RequiresPermissions("admin:storage:create")
	@RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "上传")
	@ApiOperation(value = ApiAdminConsts.Storage.CREATE)
	public Object create(@RequestParam("file") MultipartFile file) throws IOException {
		logger.info("【请求开始】操作人:[" + AuthSupport.userName()+ "] 系统管理->对象存储->上传,请求参数,file:{}", file.getOriginalFilename());
		String originalFilename = file.getOriginalFilename();
		String url = storageService.store(file.getInputStream(), file.getSize(), file.getContentType(),
				originalFilename);
		Map<String, Object> data = new HashMap<>();
		data.put("url", url);
		return ResponseUtils.ok(data);
	}

	@RequiresPermissions("admin:storage:read")
	@RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "详情")
	@ApiOperation(value = ApiAdminConsts.Storage.READ)
	@PostMapping("/read")
	@WebLog(description = ApiAdminConsts.Storage.READ)
	public Object read(@ApiParam(value = "存储对象id") @NotNull Integer id) {
		DtsStorage storageInfo = dtsStorageService.findById(id);
		if (storageInfo == null) {
			return ResponseUtils.badArgumentValue();
		}
		return ResponseUtils.ok(storageInfo);
	}

	@RequiresPermissions("admin:storage:update")
	@RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "编辑")
	@ApiOperation(value = ApiAdminConsts.Storage.UPDATE)
	@PostMapping("/update")
	@WebLog(description = ApiAdminConsts.Storage.UPDATE, persistence = true)
	public Object update(@RequestBody DtsStorage dtsStorage) {
		if (dtsStorageService.update(dtsStorage) == 0) {
			logger.error("系统管理->对象存储->编辑 错误:{}", "更新数据失败!");
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok(dtsStorage);
	}

	@RequiresPermissions("admin:storage:delete")
	@RequiresPermissionsDesc(menu = { "系统管理", "对象存储" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Storage.DELETE)
	@PostMapping("/delete")
	@WebLog(description = ApiAdminConsts.Storage.DELETE, persistence = true)
	public Object delete(@RequestBody DtsStorage dtsStorage) {
		String key = dtsStorage.getKey();
		if (StringUtils.isEmpty(key)) {
			return ResponseUtils.badArgument();
		}
		dtsStorageService.deleteByKey(key);
		storageService.delete(key);
		return ResponseUtils.ok();
	}
}
